Scroll Progress Bar

The switch statement is a control statement used to select one of many code blocks to be executed based on the value of an expression. It provides a more concise and organized way to handle multiple cases as compared to using multiple if-else statements.

Syntax:

switch (expression) {
    case value1:
        // Code to execute when expression is equal to value1
        break;

    case value2:
        // Code to execute when expression is equal to value2
        break;

    // Add more cases as needed

    default:
        // Code to execute when none of the cases match (optional)
}

expression: The value used to evaluate which case to execute.

value1, value2, etc.: Constants that represent different cases.

break: The break statement is used to exit the switch block once a matching case is found. If break is not used, the execution will continue to the next case (fall-through behavior).

Example:

#include <stdio.h>

int main() {
    int day;

    printf("Enter a number (1-7) to represent the day of the ek: ");
    scanf("%d", &day);

    switch (day) {
        case 1:
            printf("Sunday\n");
            break;

        case 2:
            printf("Monday\n");
            break;

        case 3:
            printf("Tuesday\n");
            break;

        case 4:
            printf("dnesday\n");
            break;

        case 5:
            printf("Thursday\n");
            break;

        case 6:
            printf("Friday\n");
            break;

        case 7:
            printf("Saturday\n");
            break;

        default:
            printf("Invalid input. Please enter a number beten 1 and 7.\n");
    }

    return 0;
}
Explanation:

In this example, the program takes input from the user to represent the day of the ek as a number (1-7). It then uses the switch statement to select the appropriate day name based on the entered number. For example, if the user enters 1, it will print "Sunday," for 2, it will print "Monday," and so on. If the user enters a number outside the range of 1 to 7, the default case will be executed, and it will print "Invalid input. Please enter a number beten 1 and 7."

The break statement is used after each case to exit the switch block once a matching case is found. This ensures that only the code corresponding to the matching case is executed, and the program doesn't continue to execute code in subsequent cases.

The default case is optional and is executed when none of the cases match the value of the expression. It serves as a catch-all for any input that doesn't match the specific cases.


What is the purpose of the 'switch' statement in C?


Control

What data type can be used in the 'switch' statement's expression?


Integer

In the 'switch' statement, what keyword is used for each case block's condition?


Case

What is the purpose of the 'default' case in a 'switch' statement?


Fallback

What keyword is used to exit a 'switch' statement prematurely?


Break